
package com.customize.lflistview.demo;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.ArrayAdapter;

import com.customize.lflistview.LfListView;
import com.customize.lflistview.LfListView.OnLoadMoreListener;
import com.customize.lflistview.LfListView.OnRefreshListener;
import com.customize.lflistview.R;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class MainActivity extends Activity {

    private static final int REFRESH_LIST = 1;
    private static final int LOAD_MORE = 2;
    private LfListView mListView;
    private List<String> data = new ArrayList<String>();
    private ArrayAdapter<String> mAdapter;
    private int index = 1;

    private Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case REFRESH_LIST:
                    refreshData();
                    mAdapter.notifyDataSetChanged();
                    break;
                case LOAD_MORE:
                    addData();
                    if (data.size() > 20) {
                        mListView.setMoreData(false);
                    }
                    mAdapter.notifyDataSetChanged();
                    break;
                default:
                    break;
            }
        };
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mListView = (LfListView) findViewById(R.id.listView1);
        mListView.setEmptyView(findViewById(R.id.empty));
        refreshData();
        mAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1,
                data);
        mListView.setAdapter(mAdapter);
        mListView.setOnRefreshListener(new OnRefreshListener() {

            @Override
            public void onRefreshList() {
                mHandler.sendEmptyMessageDelayed(REFRESH_LIST, 2000);
            }
        });
        mListView.setOnLoadMoreListener(new OnLoadMoreListener() {

            @Override
            public void onLoadMore() {
                mHandler.sendEmptyMessageDelayed(LOAD_MORE, 2000);
            }
        });
    }

    private void addData() {
        for (int i = 0; i < 5; i++) {
            data.add("String-" + index++);
        }
    }

    private void refreshData() {
        data.clear();
        index = 1;
        int count = new Random().nextInt(20);
        for (int i = 0; i < count; i++) {
            data.add("String-" + index++);
        }
    }

}
